package com.hw.backapi.exception;

import com.hw.common.exception.BaseException;
import com.hw.model.common.BaseResult;
import com.hw.model.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {
    /**
     * 请求数据不能解析时的异常捕获
     * @param exception
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public BaseResult exceptionHandler(HttpMessageNotReadableException exception){
        BaseResult fail = BaseResult.fail("请求数据不正确，系统未能正常解析。");
        return fail;
    }

    /**
     * 请求格式错误异常捕获
     * @param exception
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public BaseResult exceptionNotSupportHandler(HttpRequestMethodNotSupportedException exception){
        BaseResult fail = BaseResult.fail("请求方式不正确，请检查");
        return fail;
    }

    @ExceptionHandler(BaseException.class)
    public BaseResult serviceExceptionHandler(BaseException exception){
        BaseResult fail = new BaseResult(exception.getErrorCode(),exception.getMessage());
        return fail;
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResult ValidHandler(BindingResult bindingResult) {
        FieldError fieldError = bindingResult.getFieldErrors().get(0);
        return BaseResult.fail(fieldError.getDefaultMessage());
    }

    @ExceptionHandler({Exception.class})
    public BaseResult handleException(Exception exception, HttpServletResponse response) {
        log.error(exception.getMessage(), exception);
        if (exception instanceof BaseException) {
            return this.serviceExceptionHandler((BaseException) exception);
        } else if (exception instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException e = (MethodArgumentNotValidException)exception;
            String[] str = ((String[]) Objects.requireNonNull(((ObjectError)e.getBindingResult().getAllErrors().get(0)).getCodes()))[1].split("\\.");
            String message = ((ObjectError)e.getBindingResult().getAllErrors().get(0)).getDefaultMessage();
            String msg = "不能为空";
            if (msg.equals(message)) {
                message = str[1] + ":" + message;
            }

            response.setStatus(HttpStatus.BAD_REQUEST.value());
            return BaseResult.fail( message);
        } else {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//            return BaseResult.fail("服务器异常");
            return BaseResult.fail(exception.toString());
        }
    }

}
